/**
 * Copyright 2014-2015 www.fsfkj.com
 * All rights reserved.
 * 
 * @project
 * @author jipengfei
 * @version 1.0
 * @date 2015-11-23
 */
package com.eyaomall.wxmanage.common.helper;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import com.eyaomall.wxmanage.common.helper.image.IPPY;
import com.eyaomall.wxmanage.common.helper.image.Image;
import com.eyaomall.wxmanage.common.helper.image.ResPPE;
import com.eyaomall.wxmanage.common.helper.image.Tag;
import com.eyaomall.wxmanage.model.pojo.ResOss;
import com.lycheeframework.core.cmp.api.error.SECode;
import com.lycheeframework.core.cmp.api.http.GsnData;
import com.lycheeframework.core.cmp.api.http.GsnResponse;
import com.lycheeframework.core.common.helper.Properties;
import com.lycheeframework.core.common.util.encrypt.SHA256;
import com.lycheeframework.core.exception.ErrorCodeException;

/***
 * 图片上传，非oss存储
 * @author apple
 *
 */
public class ImageHelper {
	
	/**
	 * 上传图片
	 * @param key
	 * @param pic
	 * @return
	 * @throws IOException
	 */
	public static GsnData upload(String key,MultipartFile pic) throws IOException{
		String path = null;
		ImageHelper imageHelper = new ImageHelper();
		BufferedImage bi = javax.imageio.ImageIO.read(pic
				.getInputStream());
		if (bi == null) {
			throw new ErrorCodeException(SECode.s_100012);
		} else {
			Image img = imageHelper.addUploadedPic(pic);
			if (img == null)
				throw new ErrorCodeException(SECode.s_100012);

			ResPPE rp = img.getOriginal();

			if (rp != null) {
				path = rp.getRelaDirPath() + "/" + rp.getPicName()
						+ "." + rp.getExt();
			}
		}
		
		ResOss ro =  new ResOss();
		ro.setKey(key);
		ro.setFilePath(path);
		return GsnResponse.toData(ro);
	}

	/**
	 * 上传用户图片 (外部用户自己上传的图片)
	 * 
	 * @param pic
	 * @return
	 * @throws IOException
	 */
	public Image addUploadedPic(MultipartFile pic) throws IOException {
		Image image = getStores(getIPPY(Tag.uploaded.name()), pic);
		
		storeBig(pic, image.getOriginal());

		return image;
	}

	/**
	 * 生成大图
	 * 
	 * @param pic
	 * @param resPPE
	 */
	private void storeBig(MultipartFile pic, ResPPE resPPE) {
		try {
			BufferedImage img = javax.imageio.ImageIO
					.read(pic.getInputStream());
			if (img.getWidth() > 900 || img.getHeight() > 600) {
				OutputStream os = new FileOutputStream(resPPE.getFullPath());
				Thumbnails.of(pic.getInputStream()).size(900, 600)
						.toOutputStream(os);
			} else {
				FileUtils.copyInputStreamToFile(pic.getInputStream(), new File(
						resPPE.getFullPath()));
			}

		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}


	/**
	 * 返回需要存储的图片路径
	 * 
	 * @param ippy
	 * @param pic
	 * @return
	 */
	private Image getStores(IPPY ippy, MultipartFile pic) {
		Image ppes = new Image();

		try {
			String newPicName = SHA256.encrypt(
					String.valueOf(new Date().getTime())).substring(0, 24);
			String ext = FilenameUtils.getExtension(pic.getOriginalFilename());

			setOriginal(ippy, ppes, newPicName, ext);

		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}

		return ppes;
	}


	/**
	 * 设置原图
	 * 
	 * @param ippy
	 * @param image
	 * @param newPicName
	 * @param ext
	 */
	private void setOriginal(IPPY ippy, Image image, String newPicName,
			String ext) {
		ResPPE resPPE = new ResPPE();
		resPPE.setExt(ext);
		resPPE.setRelaDirPath(ippy.getRelative());
		resPPE.setPicName(newPicName);

		String fp = ippy.getFull() + "/" + newPicName + "." + ext;
		resPPE.setFullPath(fp);

		image.setOriginal(resPPE);
	}

	/**
	 * 返回图片路径
	 * 
	 * @param tag
	 * @return
	 */
	private IPPY getIPPY(String tag) {
		File rd = new File(Properties.get("store.image")); // 根目录
		if (!rd.exists()) {
			rd.mkdir();
		}

		File td = new File(rd.getPath() + "/" + tag); // 一级目录
		if (!td.exists()) {
			td.mkdir();
		}

		String timestamp = String.valueOf(new Date().getTime()).substring(0, 6); // 二级目录
		File sd = new File(td.getPath() + "/" + timestamp);
		if (!sd.exists()) {
			sd.mkdir();
		}

		IPPY ippy = new IPPY();
		ippy.setFull(sd.getPath());
		ippy.setRelative(tag + "/" + timestamp);

		return ippy;
	}
}
